const router = require('koa-router')();
const membersModel = require('../models/members');
const userModel = require('../models/user');
const multer = require('koa-multer');//文件上传
const path = require("path");
const fs = require("fs");
const { basename } = require('path');

// 配置文件上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, `${process.cwd()}/static/upLoad`)
    },
    filename: function (req, file, cb) {
        let type = file.originalname.split('.')[1]
        cb(null, `${file.fieldname}-${Date.now().toString(16)}.${type}`)
    }
})
//加载配置
var upload = multer({
    storage: storage
});
router.get('/',async ctx=>{
    var data = await membersModel.find({});
    await ctx.render("index",{data})
})

// 展示页面路由
router.get('/show',async ctx=>{
    var data = await membersModel.find({});
    await ctx.render("show",{data})
})

// 删除
router.post("/delete",async ctx=>{
    let {id} = ctx.request.body;
    await membersModel.remove({_id:id});
    ctx.redirect("back");
})
// 转跳add
router.get("/toAdd",async ctx=>{
    console.log(ctx.request.url);
    let id = ctx.request.url.split("=")[1];
    // 有id则是修改,传入需要修改的参数的信息
    if(id){
        var data = await membersModel.find({_id:id});
        console.log(data);
        await ctx.render("add",{data})
    }else{
        // 无id则是添加
        await ctx.render("add")
    }
})
// 添加&修改
router.post("/add",upload.single('file'),async (ctx,next)=>{
    let {id,name,age,like} = ctx.req.body;
    var imageUrl = ctx.req.file.filename;
    console.log(ctx.request.body);
    // console.log(typeof id);
    // 有id则是修改信息
    if(id){
        await membersModel.findByIdAndUpdate(id,{
            name,
            age,
            like,
            imageUrl,
        })
    }else{
        // 没id是添加信息

        // 保存文件
        var data = new membersModel({name,age,like,state:false,imageUrl});
        data.save(err=>{
            if(err){throw err};
        })
    }
    ctx.redirect("/");
})
// 状态更新
router.post("/state",async ctx=>{
    let {id,state} = ctx.request.body;
    // 收藏功能
    let data = await membersModel.find({_id:id});
    let obj = data[0]
    console.log('obj: ', obj);
    await userModel.updateOne({name:"zz",},{$push:{collects:obj}})

    // 改变状态
    if(state=="false"){
        var a = true
    }else{
        var a = false
    }
    await membersModel.findByIdAndUpdate(id,{
        state:a
    });
    ctx.redirect("/");
})

// 上传文件
router.post('/doUpload',upload.single('file'), async (ctx, next) => {
    var {name,rating} = ctx.req.body;

}) 

// 图片上传koa-body测试
router.get("/toUpLoadTest",async ctx=>{
    await ctx.render("upLoad");
})
router.post("/UpLoadTest",async ctx=>{
    // console.log(path.basename(ctx.request.files.fileText.path));
    let file = ctx.request.files.fileText;
    let uploadName = path.basename(file.path);
    if(file.name){
        // 将本地文件放到服务器的static的文件目录中
        // 创建可读流
        const reader = fs.createReadStream(file.path);//实现读文件file.path是上传的图片所在的路径
        // 获取上传文件扩展名
        let filePath =  process.cwd() + `/static/upLoad/${uploadName}`;//获取上传的文件名(就是传到哪了)
        console.log(filePath);
        // 创建可写流
        const upStream = fs.createWriteStream(filePath);//写入文件
        // 可读流通过管道写入可写
        reader.pipe(upStream);
    }else{
        ctx.body = (`<script>alert("请上传图片");location.href="/toUpLoadTest"</script>`)
    }
});

module.exports = router;